package cumt.kydd.authoringplatform.filter;

import cn.hutool.core.text.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        //获取请求uri
        String requestURI = request.getRequestURI();
//        System.out.println("拦截到请求：{}"+requestURI);
        //定义不需要处理请求路径
        String[] urls=new String[]{
                "/**"
//                "/**",
        };
        //定义需要处理请求路径
        String[] needurls=new String[]{
                "/platform",
                "/history",
                "/help",
                "/trash",
                "/userInfo"
        };
        //判断登录状态
        if(request.getSession().getAttribute("user")!=null){
//            System.out.println("拦截表示：用户已登录，用户信息为：{}"+request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }
        //还未登录通过输出流，返回NOTLOGIN信息，前端响应拦截器进行页面跳转
//        System.out.println("用户未登录！");

        boolean check = check(urls, requestURI);
        boolean check2 = check(needurls, requestURI);
        if(check2){
//            System.out.println("本次请求用处理:{}"+ requestURI);
            response.sendRedirect("/index");
//            filterChain.doFilter(request, response);
            return;
        }
        if(check){
//            System.out.println("本次请求不用处理:{}"+ requestURI);
            filterChain.doFilter(request, response);
            return;
        }

//        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配检查此次请求是否放行
     * @param urls
     * @param requestURI
     * @return
     */
    public static boolean check(String[] urls, String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
